// 创建工单变量
var rollData = [],
	deviceInfo = {};
$(function(){
	var parentHeight,parentWidth;
	parentHeight = $("#device-box").height() - 222;
    parentWidth = $("#device-box").width();
	$("#device-table").jqGrid({
		url: contextPath + "/Device/queryDeviceJqg",
		datatype: "json",
		height: parentHeight,
	    width: parentWidth,
		colNames:['设备编号','设备名称','设备地址','id','设备类型','设备型号','设备厂家','经度','纬度','id','项目名称','id','产品线名称','状态','备注信息','操作'],
		colModel:[
			{name:'id',index:'id',align:"center"},
			{name:'name',index:'name',align:"center"},
			{name:'addrs',index:'addrs',align:"center"},
			{name:'deviceTypeId',index:'deviceTypeId',align:"center",hidden:true},
			{name:'deviceTypeName',index:'deviceTypeName',align:"center"},
			{name:'version',index:'version',align:"center"},
			{name:'vendor',index:'vendor',align: "center"},
			{name:'longitude',index:'longitude',align:"center"},
			{name:'latitude',index:'latitude',align:"center"},
			{name:'projectId',index:'projectId',align:"center",hidden:true},
			{name:'projectName',index:'projectName',align:"center"},
			{name:'productLineId',index:'productLineId',align:"center",hidden:true},
			{name:'productLineName',index:'productLineName',align:"center"},
			{name:'source',index:'source',align:"center",hidden:true},
			{name:'note',index:'note',align:"center"},
			{name:'operate',formatter: operation,sortable: false}
		],
		sortname:'createTime',
		sortorder:'desc',
		viewrecords: true,
		multiselect: true,
		rowNum: 20,
		rowList:[5,10,20],
		pager: '#device-pager'
	});
	$("#device-table").jqGrid('navGrid', '#device-pager', {edit : false,add : false,del : false,search: false});
	// 查询产品线
	$.ajax({
        url: contextPath + "/ProductLine/queryAllProductLine",
        type: "get",
        cache: false,
        dataType: "json",
        success: function(data){
            var str = '<option value="">全部</option>';
            for (var i =0 ,len = data.length; i < len; i++) {
            	str += '<option value="' + data[i].id + '">' + data[i].name + "</option>";
            }
            $("#productLineId").html(str);
        },
        error: function(data){
            console.log(data);
            $("#productLineId").html('<option value="">数据异常</option>');
        }
    });
    // 查询设备类型
	$.ajax({
        url: contextPath + "/DeviceType/queryAllDeviceType",
        type: "get",
        cache: false,
        dataType: "json",
        success: function(data){
            var str = '<option value="">全部</option>';
            for (var i =0 ,len = data.length; i < len; i++) {
            	str += '<option value="' + data[i].id + '">' + data[i].name + "</option>";
            }
            $("#deviceTypeId").html(str);
        },
        error: function(data){
            console.log(data);
            $("#deviceTypeId").html('<option value="">数据异常</option>');
        }
    });
    // 查询按钮
    $("#query").on("click",function(){
        $("#device-table").setGridParam({
            url : contextPath + "/Device/queryDeviceJqg",
            postData : {
                queryCond:{
                    'productLineId': $('#productLineId').val()?Number($('#productLineId').val()):null,
                    'projectName': $('#projectName').val(),
                    'deviceTypeId': $('#deviceTypeId').val()?Number($('#deviceTypeId').val()):null,
                    'id': $('#deviceNum').val()
                }
            },
            page:1
        }).trigger("reloadGrid");
        deviceData = null;
    });
    // 创建工单
    $("#addWorkOrder").on('click',function(){
    	var ids = $('#device-table').jqGrid('getGridParam','selarrrow');
    	if(!ids.length){
    		toastr.error("未选择设备！");
			return;
    	}
    	for (var i = 0,len = ids.length; i < len; i++) {
    		rollData.push($('#device-table').jqGrid('getRowData',ids[i]));
    	}
    	deviceInfo = {
    		'productLineId' : rollData[0]['productLineId'],
    		'productLineName' : rollData[0]['productLineName'],
    		'projectId' : rollData[0]['projectId'],
    		'projectName' : rollData[0]['projectName'],
    		'deviceTypeId' : rollData[0]['deviceTypeId'],
    		'deviceTypeName' : rollData[0]['deviceTypeName']
    	};
		for(var i = 1,len = rollData.length; i < len; i++){
    		if(rollData[i]['productLineId'] != deviceInfo.productLineId){
    			toastr.error("选择设备的产品线不一致，无法批量创建工单！");
    			rollData = [],deviceInfo = {};
    			return;
    		}
    	}
    	for(var i = 1,len = rollData.length; i < len; i++){
    		if(rollData[i]['projectName'] != deviceInfo.projectName){
    			toastr.error("选择设备的项目不一致，无法批量创建工单！");
    			rollData = [],deviceInfo = {};
    			return;
    		}
    	}
    	for(var i = 1,len = rollData.length; i < len; i++){
    		if( rollData[i]['deviceTypeId'] != deviceInfo.deviceTypeId){
    			toastr.error("选择设备的类型不一致，无法批量创建工单！");
    			rollData = [],deviceInfo = {};
    			return;
    		}
    	}
    	location.hash = "qualitycontrol-projectGroup-addWorkOrder";
    });
    // 导入
	$('#fileupload').fileupload({
		dataType: 'json',
		done: function (e, data) {
			if(data.result.code == "1") {
				toastr.success('导入设备成功！');
			} else if(data.result.code == "2") {
				toastr.error(data.result.message,'操作失败');
			} else {
				toastr.error(data.result.message,'导入设备部分成功！');
			}
			$("#device-table").trigger("reloadGrid");
		}
	});
	// 导出
	$("#exportDeviceList").on('click',function(){
		var url = "Device/exportDeviceList";
		window.open(url);
    });
});
function operation(cellvalue,options,rowObject){
	var str = "";
	// if([[${#authorization.expression('hasAuthority(''modifyAuthority'')')}]]){
		str += "<input class='btn btn-primary btn-xs modify' type='button' value='修改'>&nbsp;";
	// }
	// if([[${#authorization.expression('hasAuthority(''deleteAuthority'')')}]]){
		str += "<input class='btn btn-danger btn-xs del' type='button' value='删除' data-toggle='modal' data-target='.bs-example-modal-sm'>";
	// }
    return str;
}
//修改
var deviceData = null;
/* 修改 || 删除 */
$("#device-table").on('click','.modify,.del',function(){
	var id = $(this).parent().parent().attr('id');
	deviceData = $("#device-table").jqGrid('getRowData',id);
    delete deviceData.operate;
    if($(this).hasClass("modify")){
   		window.location.hash = "qualitycontrol-projectGroup-modifyDevice";
    }else{
    	deviceData.productLineId = Number(deviceData.productLineId);
    	deviceData.deviceTypeId = Number(deviceData.deviceTypeId);
    	deviceData.latitude = Number(deviceData.latitude);
    	deviceData.longitude = Number(deviceData.longitude);
    	deviceData.projectId = Number(deviceData.projectId);
    }
});
$("#deleteData").on('click',function(){
	$.ajax({
        url:contextPath + '/Device/deleteDevice',
        type:"delete",
        contentType:"application/json",
        dataType:"json",
        data: JSON.stringify(deviceData),
        success:function(data){
            if(data.code == 1){
                $('#deleteNotice').modal('hide');
                toastr.success('删除成功！');
                $("#device-table").setGridParam({
                    url : contextPath + "/Device/queryDeviceJqg",
                    postData : {
                        queryCond:{
                            'productLineId': $('#productLineId').val()?Number($('#productLineId').val()):null,
                            'projectName': $('#projectName').val(),
                            'deviceTypeId': $('#deviceTypeId').val()?Number($('#deviceTypeId').val()):null,
                            'id': $('#deviceNum').val()
                        }
                    },
					page:1
                }).trigger("reloadGrid");
                deviceData = null;
            }else{
                toastr.error(data.message,'删除失败！');
            }
        },
        error:function(data){
        	console.log(data);
            toastr.error('操作失败，请稍后再试！');
        }
    });
});
$(window).resize(function(){
	$("#device-table").setGridWidth($('#device-box').width());
	$("#device-table").setGridHeight($('#device-box').height() - 222);
});
//侧边栏缩小时，实时的给jqgrid的宽和高赋值
$("#asidebarSwitch").on('click',function() {
    var time = 0;
    var set = setInterval(function (){
        $("#device-table").setGridWidth($('#device-box').width());　　
        $("#device-table").setGridHeight($('#device-box').height() - 222);
        time++;
        if(time >= 200){
            clearInterval(set);
        }
    },time);
});　